<?php
namespace app\admin\controller;

use think\Config;
use think\Controller;
use think\Db;
use think\Session;
use think\Cache;

/**
 * 后台登录
 * Class Login
 * @package app\admin\controller
 */
class Login extends Controller
{

    protected function _initialize()
    {
        parent::_initialize();
        $this->getProConfig();
    }
    /**
     * 后台登录
     * @return mixed
     */
    public function index()
    {
        return $this->fetch();
    }
    /**
     * 参数配置信息
     */
    protected function getProConfig()
    {
        if (Cache::has('site_pro_config')) {
            $site_pro_config = Cache::get('site_pro_config');
        } else {
            $site_pro_config = Db::name('system')->field('value')->where('name', 'site_pro_config')->find();
            $site_pro_config = unserialize($site_pro_config['value']);
            Cache::set('site_pro_config', $site_pro_config);
        }
        $this->proConfig = $site_pro_config;
    }

    /**
     * 登录验证
     * @return string
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->only(['username', 'password', 'verify']);
            $validate_result = $this->validate($data, 'Login');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $where['username'] = $data['username'];
                $where['password'] = md5($data['password'] . Config::get('salt'));

                $admin_user = Db::name('admin_user')->field('id,username,status')->where($where)->find();

                if (!empty($admin_user)) {
                    if ($admin_user['status'] != 1) {
                        $this->error('当前用户已禁用');
                    } else {
                        Session::set('admin_id', $admin_user['id']);
                        Session::set('admin_name', $admin_user['username']);
                        Db::name('admin_user')->update(
                            [
                                'last_login_time' => date('Y-m-d H:i:s', time()),
                                'last_login_ip'   => $this->request->ip(),
                                'id'              => $admin_user['id']
                            ]
                        );
                        $this->success('登录成功', 'admin/index/index');
                    }
                } else {
                    $this->error('用户名或密码错误');
                }
            }
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Session::delete('admin_id');
        Session::delete('admin_name');
        $this->success('退出成功', 'admin/login/index');
    }


    /**
     * 定时任务
     * 余额宝分红
     * http://www.txfdzswvip.com/admin/login/bonus.html
     * http://www.richs.com/admin/login/bonus.html
     * 释放注册积分
     * http://www.txfdzswvip.com/admin/login/regIntegralBonus.html
     * 消费积分释放
     * http://www.txfdzswvip.com/admin/login/consumeIntegralBonus.html
     * 推荐积分释放
     * http://www.txfdzswvip.com/admin/login/shareIntegralBonus.html
     * 
     */

    /**
     * 余额宝分红
     */
    public function bonus(){

        $now = time();

        //$config = Db::name('balance_config')->field('*')->where(array('id'=>6))->find();

        //$rate = $config['num'];
        $rate = $this->proConfig['balance_ratio']*1000;


        Db::startTrans();

        $r1 = Db::execute("insert into
                                os_fund_log (
                                  num,time,uid,description,change_type,from_id,before_num,later_num,wallet_type
                                )
                            select
                              balance*$rate/1000,$now,id,'余额宝增值',9,0,balance,balance+balance*$rate/1000,7
                             
                            from
                              os_user
                            where
                              balance > 0
                              ");
        // 增加用户分红
        $r3 = Db::execute("UPDATE os_user
                                    SET balance = balance + (
	                                  SELECT
		                                num
	                                  FROM
		                                os_fund_log AS f
	                                  WHERE
		                                wallet_type = 7
                                        and uid = os_user.id
	                                    AND to_days(FROM_UNIXTIME(f.time, '%Y-%m-%d %H:%i:%S')) = to_days(now())
                                      )
                                WHERE
	                                balance > 0
                              ");
        //返回

        if($r1 > -1 && $r3 > -1){
            Db::commit();

            return 1;

        }else{
            Db::rollback();
            return false;
        }

    }


    /**
 * 注册积分释放
 */
    public function regIntegralBonus(){

        $now = time();

        //$config = Db::name('balance_config')->field('*')->where(array('id'=>6))->find();

        //$rate = $config['num'];
        $rate = $this->proConfig['reg_ratio']*1000;

        Db::startTrans();

        $r1 = Db::execute("insert into
                                os_fund_log (
                                  num,time,uid,description,change_type,from_id,before_num,later_num,wallet_type
                                )
                            select
                              reg_integral*$rate/1000,$now,id,'注册积分释放',8,0,re_reg_integral,re_reg_integral+reg_integral*$rate/1000,2
                             
                            from
                              os_user
                            where
                              reg_integral > 10
                              ");

        // 增加用户分红
        $r3 = Db::execute("UPDATE os_user
                                    SET re_reg_integral = re_reg_integral + (
	                                  SELECT
		                                num
	                                  FROM
		                                os_fund_log AS f
	                                  WHERE
		                                wallet_type = 2
                                        and uid = os_user.id
	                                    AND to_days(FROM_UNIXTIME(f.time, '%Y-%m-%d %H:%i:%S')) = to_days(now())
                                      ),
                                      reg_integral = reg_integral - (
                                    SELECT
                                    num
                                    FROM
                                    os_fund_log AS f
                                    WHERE
                                    wallet_type = 2
                                        and uid = os_user.id
                                      AND to_days(FROM_UNIXTIME(f.time, '%Y-%m-%d %H:%i:%S')) = to_days(now())
                                      )
                                WHERE
	                                reg_integral > 10
                              ");

        //返回

        if($r1 > -1 && $r3 > -1){
            Db::commit();

            return 1;

        }else{
            Db::rollback();
            return false;
        }

    }

    /**
     * 消费积分释放
     */
    public function consumeIntegralBonus(){

        $now = time();

        //$config = Db::name('balance_config')->field('*')->where(array('id'=>6))->find();

        //$rate = $config['num'];
        $rate = $this->proConfig['consume_ratio']*1000;

        Db::startTrans();

        $r1 = Db::execute("insert into
                                os_fund_log (
                                  num,time,uid,description,change_type,from_id,before_num,later_num,wallet_type
                                )
                            select
                              consume_integral*$rate/1000,$now,id,'消费积分释放',8,0,re_consume_integral,re_consume_integral+consume_integral*$rate/1000,4
                             
                            from
                              os_user
                            where
                              consume_integral > 10
                              ");

        // 增加用户分红
        $r3 = Db::execute("UPDATE os_user
                                    SET re_consume_integral = re_consume_integral + (
	                                  SELECT
		                                num
	                                  FROM
		                                os_fund_log AS f
	                                  WHERE
		                                wallet_type = 4
                                        and uid = os_user.id
	                                    AND to_days(FROM_UNIXTIME(f.time, '%Y-%m-%d %H:%i:%S')) = to_days(now())
                                      ),
                                      consume_integral = consume_integral - (
                                    SELECT
                                    num
                                    FROM
                                    os_fund_log AS f
                                    WHERE
                                    wallet_type = 4
                                        and uid = os_user.id
                                      AND to_days(FROM_UNIXTIME(f.time, '%Y-%m-%d %H:%i:%S')) = to_days(now())
                                      )
                                WHERE
	                                consume_integral > 10
                              ");

        //返回

        if($r1 > -1 && $r3 > -1){
            Db::commit();

            return 1;

        }else{
            Db::rollback();
            return false;
        }

    }


    /**
     * 分享积分释放
     */
    public function shareIntegralBonus(){

        $now = time();

        //$config = Db::name('balance_config')->field('*')->where(array('id'=>6))->find();

        //$rate = $config['num'];
        $rate = $this->proConfig['share_ratio']*1000;

        Db::startTrans();

        $r1 = Db::execute("insert into
                                os_fund_log (
                                  num,time,uid,description,change_type,from_id,before_num,later_num,wallet_type
                                )
                            select
                              share_integral*$rate/1000,$now,id,'分享积分释放',8,0,re_share_integral,re_share_integral+share_integral*$rate/1000,6
                             
                            from
                              os_user
                            where
                              share_integral > 10
                              ");

        // 增加用户分红
        $r3 = Db::execute("UPDATE os_user
                                    SET re_share_integral = re_share_integral + (
	                                  SELECT
		                                num
	                                  FROM
		                                os_fund_log AS f
	                                  WHERE
		                                wallet_type = 6
                                        and uid = os_user.id
	                                    AND to_days(FROM_UNIXTIME(f.time, '%Y-%m-%d %H:%i:%S')) = to_days(now())
                                      ),
                                      share_integral = share_integral - (
                                    SELECT
                                    num
                                    FROM
                                    os_fund_log AS f
                                    WHERE
                                    wallet_type = 6
                                        and uid = os_user.id
                                      AND to_days(FROM_UNIXTIME(f.time, '%Y-%m-%d %H:%i:%S')) = to_days(now())
                                      )
                                WHERE
	                                share_integral > 10
                              ");

        //返回

        if($r1 > -1 && $r3 > -1){
            Db::commit();

            return 1;

        }else{
            Db::rollback();
            return false;
        }

    }
}
